<?php
/*
*后台属性展示
*/
namespace app\admin\controller;
use think\Controller;
use think\Request;
use \think\Db;
use app\admin\lib\Tree;
use app\admin\lib\Detail;
class Product extends Base{
    //车辆列表
    public function index(){
      $db = Db::name('product');
      $list = $db->order('sort asc')->paginate(10);
      $page = $list->render();
      // 模板变量赋值
      $this->assign('list', $list);
      $this->assign('page', $page);
      $pin = $this ->select_class_name();
        // dump($list);
      $this->assign('pname', $pin);

      //获取品牌名称
      return $this->fetch();
    }

  // 品牌
    //品牌列表
    public function classlist(){
       $db = Db::table('jun_product_class');
       $list = $db->order('name asc')->select();
       $lists =  Tree::findmenu($list,'---');
       $this->assign('list',$lists);
        return $this->fetch();
     }
    //品牌添加
    public function addclass(){
       if ($_POST['name']=='') {
         $this->error('请上传品名称');die;
       }
      $file = request()->file('pic');
          if($file){
              $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
              if($info){
                  $_POST['pic'] = '/public/uploads/'.$info->getSaveName();
              }
          }
       $ok = Db::table('jun_product_class')->insert($_POST);
       if ($ok) {
         $this->success('操作成功');
       }else{
         $this->error('操作失败');
       }
     }
    //删除品牌
    public function delclass(){
       $request = Request::instance();//getid
       $getid = $request->route();
       $ok = Db::table('jun_product_class')->where('id',$getid['id'])->delete();
       if($ok){
         $this->success('删除成功');
       }else{
         $this->success('删除失败');
       }
     }

     //异步提交
    public function upclass(){
       $db = Db::table('jun_product_class');
       $name = $_POST['name'];
       $id = $_POST['id'];
       $ok = $db->where('id',$id)->update(['name'=> $name]);
       if($ok){
         $arr = ['sutart'=>'操作成功'];
         echo json_encode($arr);
       }else{
         $arr = ['sutart'=>'操作失败'];
         echo json_encode($arr);
       }
      }
      //异步更改id
      //异步上传图片
    public function upclass_uid(){
       $db = Db::table('jun_product_class');
       $name = $_POST['name'];
       $id = $_POST['id'];
       $ok = $db->where('id',$id)->update(['uid'=> $name]);
       if($ok){
         $arr = ['sutart'=>'操作成功'];
         echo json_encode($arr);
       }else{
         $arr = ['sutart'=>'操作失败'];
         echo json_encode($arr);
       }
      }
     //品牌添加
    public function addclass_pic(){
         $file = request()->file('pic');
           if($file){
               $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
               if($info){
                   $pic = '/uploads/'.$info->getSaveName();
               }
           }
          $result = Db::table('jun_product_class')
           ->where('id',$_POST['id'])
           ->update(['pic'=>$pic]);
          if($result){
              $arr = [
                'status'=>1,
                'imgurl'=>$pic
              ];
          }else{
            $arr = array(
                'status'=>0
             );

          }
           echo json_encode($arr);
        }

      //添加二级菜单
     //添加二级菜单
    public function addlevel(){
           $db = Db::table('jun_product_class');
           $request = Request::instance();//getid
           $getid = $request->route();
           $ok = $db->insert(['name'=>'新二级菜单','uid'=>$getid['id']]);
           if ($ok) {
             $this->success('添加成功');
           }else{
             $this->error('添加失败');
           }
      }
  // 品牌
  //型号
    //型号列表
    public function modellist(){
      $db = Db::name('product_subclass');
      $request = Request::instance();//getid
      $getid = $request->route();
      $list = $db->order('n asc')->where('pid',$getid['id'])->select();
      $lists =  Tree::findmenu($list,'---');
      // dump($lists);
      //获取上级品牌名称

      $name = $this->select_class_name();
      // dump($name);
      $this->assign('classname',$name);
      $this->assign('list',$lists);
      $this->assign('pid',$getid['id']);
       return $this->fetch();
    }
    //添加型号
    public function addsubclass(){
       if ($_POST['name']=='') {
         $this->error('请上传品名称');die;
       }
        $data['n']  = $_POST['name'];
        $data['uid']  = $_POST['uid'];
        $data['i']  = $_POST['i'];
        $data['pid']  = $_POST['pid'];
       $ok = Db::table('jun_product_subclass')->insert($data);
       if ($ok) {
         $this->success('操作成功');
       }else{
         $this->error('操作失败');
       }
     }
    //异步修改型号
    public function ajax_upsubclass(){
      $db = Db::name('product_subclass');
      $data['n'] = $_POST['n'];
      $data['i'] = $_POST['i'];
      $data['p'] = $_POST['p'];
      $id = $_POST['id'];
      $ok = $db->where('id',$id)->update($data);
      if($ok){
        $arr = ['sutart'=>'操作成功'];
        echo json_encode($arr);
      }else{
        $arr = ['sutart'=>'操作失败'];
        echo json_encode($arr);
      }
    }
    //通用获取品牌名称
    public function select_class_name(){
      $db = Db::name('product_class');
      $list = $db->select();
      foreach ($list as $key => $value) {
        $name[$value['id']] = $value['name'];
      }
      // dump($list);
      return $name;
    }

    //删除型号
    public function delsubclass(){
       $request = Request::instance();//getid
       $getid = $request->route();
       $ok = Db::name('product_subclass')->where('id',$getid['id'])->delete();
       if($ok){
         $this->success('删除成功');
       }else{
         $this->success('删除失败');
       }
     }
  //型号


    //添加车辆
    public function addproduct(){
        //查询首付
        $att_arr = $this->attribute(1);
        $att_arr0 =  Detail::details($att_arr,'dow_payments_name','dow_payments_title','dow_payments_remarks');
        $this->assign('attr',$att_arr0);

        // 还款年限
        $repayments = $this->attribute(2);
        $repayments0 =  Detail::details($repayments,'repayments_name','repayments_title','remarks');

        // dump($repayments0);die;

        $this->assign('nianxian',$repayments0);

        // 商业保障
        $baozhang = $this->attribute(3);
          $baozhang0 =  Detail::details($baozhang,'commercial_insurance_name','commercial_insurance_title','commercial_insurance_remarks');
        $this->assign('baozhang',$baozhang0);

        // 必要收费
        $huafei = $this->attribute(4);
        $huafei0 = Detail::details($huafei,'necessary_charges_name','necessary_charges_title','necessary_charges_remarks');
        $this->assign('huafei',$huafei0);
        //车辆级别
        $attribute = Db::name('attribute');
        $attributelist = $attribute->where('id',5)->find();
        $conts = json_decode($attributelist['content'],true);
        $this->assign('attributelist',$conts);


        //显示分类
        $product_class = Db::name('product_class');
        //通用查询车辆上级名称
        $classname = $product_class->select();
        $namelist= Tree::findmenu($classname,'---');
        sort($namelist);
        $this->assign('classname',$namelist);

        // dump($namelist);
      return $this->fetch();
    }
    //异步获取型号
    public function ajax_classname(){

      $product_class = Db::name('product_subclass');
      $data['pid'] = $_POST['id'];
      $list = $product_class->where($data)->select();

      foreach ($list as $key => $value) {

          if ($value['n']!='0') {
            $arr[] =$value;
          }

      }
      // $namelist= Tree::findmenu($list,'---',$_POST['id']);
      // sort($list);
      // dump($_POST);
      // dump($namelist);
      echo json_encode($arr);


    }

    //车辆显示
    public function upproduct(){
      // getid
      $request = Request::instance();//getid
      $getid = $request->route();
      $product = Db::name('product');
      $product_class = Db::name('product_class');
      if($getid){
        $li = $product->where('id',$getid['id'])->find();
      }


      //通用查询车辆上级名称
      $classname = $product_class->select();
      $namelist1= Tree::findmenu($classname,'---');
      sort($namelist1);
      $this->assign('classname',$namelist1);

        //查询数据库有没有对应的json
        // 首付比例

        // dump($li);die;
      if ($li['dow_payments']) {
        $att_arr = json_decode($li['dow_payments'],true);

        $this->assign('attr',$att_arr);
      }else{
        //查询首付
        $att_arr = $this->attribute(1);

          $att_arr0 =  Detail::details($att_arr,'dow_payments_name','dow_payments_title','dow_payments_remarks');
          // dump($att_arr0);
        $this->assign('attr',$att_arr0);
      }
      if ($li['repayments']) {
        // 还款年限
        $repayments = json_decode($li['repayments'],true);
        $this->assign('nianxian',$repayments);
      }else{
        // 还款年限
        $repayments = $this->attribute(2);
        $repayments0 =  Detail::details($repayments,'repayments_name','repayments_title','repayments_remarks');


        $this->assign('nianxian',$repayments0);
      }


      if ($li['commercial_insurance']) {
        // 商业保障
        $baozhang = json_decode($li['commercial_insurance'],true);
        $this->assign('baozhang',$baozhang);

      }else{
        // 商业保障
        $baozhang = $this->attribute(3);
          $baozhang0 =  Detail::details($baozhang,'commercial_insurance_name','commercial_insurance_title','commercial_insurance_remarks');
        $this->assign('baozhang',$baozhang0);
      }

      if ($li['necessary_charges']) {
        // 必要收费
        $huafei = json_decode($li['necessary_charges'],true);
        $this->assign('huafei',$huafei);
      }else{
        // 必要收费
        $huafei = $this->attribute(4);
        $huafei0 = Detail::details($huafei,'necessary_charges_name','necessary_charges_title','necessary_charges_remarks');
        $this->assign('huafei',$huafei0);
      }
      // dump($li);
      //查询车辆详细
        $this->assign('name',$li);
        //品牌名称
        $pname = $this ->select_class_name();
        $this->assign('pname',$pname);

        //通用查询车辆上级名称
        $classname = $product_class->select();
        $namelist= Tree::nextlevel($classname,$li['pid']);
        sort($namelist);
        $pnames = '';
        foreach ($namelist as $key => $value) {
          $pnames .= $value['name'].$value['html'];
        }
        $this->assign('calssnames',$pnames);

        //车辆级别
        $attribute = Db::name('attribute');
        $attributelist = $attribute->where('id',5)->find();
        $conts = json_decode($attributelist['content'],true);
        $this->assign('attributelist',$conts);

        //配置
        $configure = json_decode($li['configure'],true);

            $this->assign('configure',$configure['result']);


        //分润
        $this->assign('fenrun',json_decode($li['profit']));

        //显示图片
        $this->assign('piclist',json_decode($li['pic']));

        // 对比
        $contrast = json_decode($li['contrast'],true);
        $contrastjson = $contrast['duibi'];
        $this->assign( 'jbc_title', json_decode($contrastjson['jbc_title'],true));
        $this->assign( 'jbc_titles', json_decode($contrastjson['jbc_titles'],true));
        $this->assign( 'qita_title', json_decode($contrastjson['qita_title'],true));

          // dump(json_decode($contrastjson['qita_title'],true));



        // dump(json_decode($li['pic']));
      return $this->fetch();
    }

    //修改车辆信息
  public function upproducts(){
      //首付比例
      $data['dow_payments'] = Detail::detaillist1(
        $_POST['dow_payments_name'],
        $_POST['dow_payments_title'],
        'dow_payments_name',
        'dow_payments_title'

      );

      // dump($data);die;
      //还款年限
      $data['repayments'] = Detail::detaillist(
        $_POST['repayments_name'],
        $_POST['repayments_title'],
        $_POST['repayments_remarks'],
        'repayments_name',
        'repayments_title',
        'repayments_remarks'
      );
      // dump($data);die;
      // 商业保险
       $data['commercial_insurance'] = Detail::detaillist1(
         $_POST['commercial_insurance_name'],
         $_POST['commercial_insurance_title'],
         'commercial_insurance_name',
         'commercial_insurance_title'
       );
      // 必要收费
       $data['necessary_charges'] = Detail::detaillist1(
         $_POST['necessary_charges_name'],
         $_POST['necessary_charges_title'],
         'necessary_charges_name',
         'necessary_charges_title'
       );
      $data['name'] = $_POST['name'];//配置名称
      $data['colors'] = $_POST['colors'];//颜色
      $data['title'] = $_POST['title'];//车辆名称
      if (isset($_POST['uid'])) {
        $data['uid'] = $_POST['uid'];//颜色
      }

      //超低首付
      if (isset($_POST['high'])) {
        $data['high'] = $_POST['high'];
      }else{
          $data['high'] = 0;
      }
      //超低月供
      if (isset($_POST['low'])) {
        $data['low'] = $_POST['low'];
      }else{
          $data['low'] = 0;
      }
      //推荐
      if (isset($_POST['rec'])) {
        $data['rec'] = $_POST['rec'];
      }else{
          $data['rec'] = 0;
      }
      //最高直降
      if (isset($_POST['direct'])) {
        $data['direct'] = $_POST['direct'];
      }else{
          $data['direct'] = 0;
      }
      //热销
      if (isset($_POST['hot'])) {
        $data['hot'] = $_POST['hot'];
      }else{
          $data['hot'] = 0;
      }

      $data['package_price'] = $_POST['package_price'];//包牌价
      $data['level'] = $_POST['levels'];//车辆级别

      if (isset($_POST['shelf'])) {
        $data['shelf'] = $_POST['shelf'];//是否上架   0不上架    1上架
      }else{
        $data['shelf'] = 0;//是否上架   0不上架    1上架
      }
      $data['profit'] = json_encode($_POST['profit']);//分润
      $data['remarks'] = $_POST['remarks'];//备注
      $data['content'] = $_POST['content'];//详情



      $data['guidance_price'] = $_POST['guidance_price'];//指导价
      $data['purpose'] = $_POST['purpose'];//用途
      $data['car_model'] = $_POST['car_model'];//车型
      $data['transmission'] = $_POST['transmission'];//变速箱
      $data['energy'] = $_POST['energy'];//能源
      $data['displacements'] = $_POST['displacements'];//排量
      $data['Intake_mode'] = $_POST['Intake_mode'];//进气方式
      $data['driving_mode'] = $_POST['driving_mode'];//驱动方式
      $data['national_level'] = $_POST['national_level'];//国级
      $data['vehicle_price'] = $_POST['vehicle_price'];//汽车总价

      //骏宝驰对比
      $duibi['duibi'] = [
          'jbc_title' => json_encode($_POST['jbc_title']),
          'jbc_titles' => json_encode($_POST['jbc_titles']),
          'qita_title' => json_encode($_POST['qita_title']),
      ];
      $data['contrast'] = json_encode($duibi);

      $data['configure'] = Detail::detailxianxi($_POST);//车辆配置



      if (isset($_POST['pic'])) {
        $data['pic'] = json_encode($_POST['pic']);//图片
      }
      if (isset($_POST['id'])) {
        $ok = Db::table('jun_product')->where('id', $_POST['id'])->update($data);
        if ($ok) {
          $this->success('修改成功');
        }else{
          $this->error('操作失败');
        }
      }else{
        $ok = Db::table('jun_product')->insert($data);
        if ($ok) {
          $this->success('添加成功');
        }else{
          $this->error('操作失败');
        }
      }
      // $data['addteime'] =time();//时间

    }
    //通用异步上传图片
    public function ajaxuploads(){
      $file = request()->file('file');
        if($file){
            $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
            if($info){
                $pic = '/uploads/'.$info->getSaveName();
            }
        }
        $arr = [
            'status' =>'1',
            'path' =>$pic,
        ];
        echo json_encode($arr);
    }


    //通用查询属性表
    public function attribute($id){
        $attribute = Db::table('jun_attribute')->where('id',$id)->find();
        $att_arr = json_decode($attribute['content'],true);
        return $att_arr;
    }
    //查询车辆信息
    public function select_che(){
      $file_path = "/Applications/MAMP/htdocs/public/rand.txt";
              if(file_exists($file_path)){
                  $str = file_get_contents($file_path);//将整个文件内容读入到一个字符串中
                  $strs = explode("\r\n", $str);
              }
              $data = json_decode($strs[0],true);
              $arr = $data['result'];
              foreach ($arr as $key => $value) {
                  $arrd[] = $value;
              }
              // $this->addclass_a($arrd);
              dump($arrd);
    }

    //循环
    public function addclass_a($arr,$uid = '0'){
      $db = Db::name('product_class');
      foreach ($arr as $key => $value) {
        if(isset($value['L'])){
          $L =$value['L'];
        }else{
          $L =0;
        }
          $data = [
            'name' =>$value['N'],
             'uid' => $uid,
             'i' => $value['I'],
             'l' => $L,
           ];
           $id = $db->insertGetId($data);
          if (isset($arr[$key]['List'])) {
           self::addclass_a($value['List'],$id);
          }
      }
    }




    //批量添加型号
    public function select_subclass(){
      $db = Db::table('jun_product_class');
      $list = $db->where('id>1793')->select();
      $lists =  Tree::findmenu($list,'---');
      // dump(count($list));
      // die;
      // 1793
      // $keys = 'efb07e339b6f43f8be398271a15943f1';
      // $keys = 'd475efa64aa24f23ba4532464a3205bd';
      // $keys = 'd475efa64aa24f23ba4532464a3205bd';
      // $keys = '9a8c68d60f844070b7501d71e5feea7f';
      $keys = '4685721034734ce298f16fd398f7d4cc';//ok
      foreach ($lists as $key => $value) {
        if ($value['level'] == 3) {
          $arr = $this->get_curl($value['i'],$keys);
          $data = json_decode($arr,true);
          dump($data);die;
          $ok = $this->addclass_xinghao($data['result']['List'],'',$value['id']);
          if ($ok) {
            echo "ok".$value['id'];
            echo "<br>";
          }else{
            echo $value['id'];
            echo "<br>on";
          }
        }
      }
    }
    //循环型号
    public function addclass_xinghao($arr,$uid = 0,$pid){
      $db = Db::name('product_subclass');
      foreach ($arr as $key => $value) {
        if(isset($value['P'])){
          $P =$value['P'];
        }else{
          $P =0;
        }
        if(isset($value['N'])){
          $n =$value['N'];
        }else{
          $n =0;
        }
          $data = [
            'n' =>$n,
             'uid' => $uid,
             'pid' => $pid,
             'i' => $value['I'],
             'p' => $P,
           ];
           $id = $db->insertGetId($data);
          if (isset($arr[$key]['List'])) {
           self::addclass_xinghao($value['List'],$id,$pid);
          }
      }
    }

    //异步查询品牌
    public function ajax_product(){
      $db = Db::table('jun_product_class');
      // 查询状态为1的用户数据 并且每页显示10条数据
      $page = $_POST['page'];
      $list = $db->paginate($page);
      $lists =  Tree::findmenu($list,'---');
      if ($lists) {
        echo json_encode($lists);
      }else{
        echo "{ok:'on'}";
      }


      // [0] => array(9) {
      //   ["id"] => int(72)
      //   ["uid"] => int(0)
      //   ["name"] => string(12) "AC Schnitzer"
      //   ["pic"] => string(0) ""
      //   ["addtime"] => int(0)
      //   ["i"] => int(117)
      //   ["l"] => string(1) "A"
      //   ["level"] => int(1)
      //   ["html"] => string(0) ""
      // }
      // dump($lists);

    }

    //异步查询车辆
    public function ajax_product_view(){

      $db = Db::name('product_subclass');
      $list = $db->order('n asc')->select();
      $lists =  Tree::findmenu($list,'------');
      // and $value['id'] < 700
      foreach ($lists as $key => $value) {
        if($value['level'] == 3 && $value['id'] > 630 ) {
          // $this->addproducts($value);


                }



      }
      die;
    }
    //批量车型详细信息
    public function addproducts($name){
      $keys = '4685721034734ce298f16fd398f7d4cc';//ok
      $data = $this->get_curl_x($name['i'],$keys);
      $value = json_decode($data,true);
      $imgs = ['img'=>$value['result']["基本参数"]['img']];
      $img = json_encode($imgs);
      $datas['uid'] = $name['id'];//上级型号ID
      $datas['pid'] = $name['uid'];//型号上级ID
      $datas['cid'] = $name['pid'];//品牌ID
      $datas['high'] = 0;//超低首付
      $datas['low'] = 0;//超低月供
      $datas['direct'] = 0;//最高直降
      $datas['rec'] = 0;//推荐
      $datas['hot'] = 0;//热销
      $datas['sort'] = 100;//排序
      $datas['name'] = $name['n'];//车辆名称
      $datas['profit'] = '0';//分润（json）
      $datas['package_price'] = $name['p'];//包牌价
      $datas['level'] = '0';//车辆级别
      $datas['pic'] = $img;//车辆图片(json)
      $datas['dow_payments'] = '0';//首付(json)
      $datas['repayments'] = '0';//还款年限(json)
      $datas['necessary_charges'] = '0';//必要收费(json)
      $datas['commercial_insurance'] = '0';//商业保险（json）
      $datas['shelf'] = 1;//是否上架 （0未上架， 1上架中）
      $datas['configure'] = $data;//车辆配置（json）
      $datas['remarks'] = '0';//备注
      $datas['addteime'] = time();//上架时间
      // dump($datas);
      $db = Db::name('product');
      $db->insert($datas);
      echo "ok";

      }




    //curl系列
    public function get_curl($id,$key){
          $curl = curl_init();
          curl_setopt_array($curl, array(
            CURLOPT_URL => "http://apis.haoservice.com/lifeservice/car/GetModel/?id=".$id."&key=".$key,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "GET",
          ));
          $response = curl_exec($curl);
          $err = curl_error($curl);

          curl_close($curl);

          if ($err) {
            return "cURL Error #:" . $err;
          } else {
            return $response;
          }

    }

    //curl详细
    public function get_curl_x($id,$key){

          $curl = curl_init();
          curl_setopt_array($curl, array(
          CURLOPT_URL => "http://apis.haoservice.com/lifeservice/car?id=".$id."&key=".$key,
          CURLOPT_RETURNTRANSFER => true,
          CURLOPT_ENCODING => "",
          CURLOPT_MAXREDIRS => 10,
          CURLOPT_TIMEOUT => 30,
          CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
          CURLOPT_CUSTOMREQUEST => "GET",
          ));

          $response = curl_exec($curl);
          $err = curl_error($curl);

          curl_close($curl);
          if ($err) {
            return "cURL Error #:" . $err;
          } else {
            return $response;
          }

    }




















}
